package com.yy.utils;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PDFUtil {

    /**
     * 将pdf转成png格式并返回png的地址
     * @param pdfAddress
     * @return  返回png的绝对路径
     */
    public static String  pdfToPhoto1(String pdfAddress) {
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(pdfAddress);
        String fileName = file.getName();
        PDDocument doc = null;
        File png = null;
        try {
            doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();

            for (int j = 0; j < pageCount; j++) {
                BufferedImage image = renderer.renderImageWithDPI(j, 144); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                png = new File(pdfAddress.substring(0,pdfAddress.lastIndexOf("\\")) + File.separator + fileName.substring(0,fileName.lastIndexOf(".pdf")) + ".png");
                ImageIO.write(image, "png",png);
            }
            System.out.println("pdf转换图片成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                doc.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return png.getAbsolutePath();
    }


        /**
         *自由确定起始页和终止页
         * @param fileAddress 文件地址
         * @param filename pdf文件名
         * @param indexOfStart 开始页  开始转换的页码，从0开始
         * @param indexOfEnd 结束页  停止转换的页码，-1为全部
         * @param type 图片类型
         */
        public static void pdfToPhoto2(String fileAddress,String filename,int indexOfStart,int indexOfEnd,String type) {
            // 将pdf装图片 并且自定义图片得格式大小
            File file = new File(fileAddress+"\\"+filename+".pdf");
            try {
                PDDocument doc = PDDocument.load(file);
                PDFRenderer renderer = new PDFRenderer(doc);
                int pageCount = doc.getNumberOfPages();
                for (int i = indexOfStart; i < indexOfEnd; i++) {
                    BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                    // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                    ImageIO.write(image, type, new File(fileAddress+"\\"+filename+"_"+(i+1)+"."+type));
                }
                System.out.println("pdf转换图片成功！");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}
